package cn.yitun.chat.yitunserverimapicore.business.chat.service.impl;

import cn.yitun.chat.yituncommonmessage.result.ResultMessage;
import cn.yitun.chat.yitunservercommonlib.crud.yitun.CrudServiceImpl;
import cn.yitun.chat.yitunservercommonlib.dataentity.data.base.chat.ChatItem;
import cn.yitun.chat.yitunservercommonlib.dataentity.data.base.chat.UserChatHistoryDto;
import cn.yitun.chat.yitunservercommonlib.dataentity.data.base.chat.UserOfflineCount;
import cn.yitun.chat.yitunservercommonlib.dataentity.data.core.chat.UserChatHistory;
import cn.yitun.chat.yitunservercommonlib.dataentity.dto.userchat.UserChatContentDto;
import cn.yitun.chat.yitunservercommonlib.dataentity.po.userchat.UserChatContentInfo;
import cn.yitun.chat.yitunservercommonlib.dataentity.vo.system.user.UserVo;
import cn.yitun.chat.yitunservercommonlib.dataentity.vo.userchat.UserChatContentVo;
import cn.yitun.chat.yitunservercommonlib.enums.userChat.UserChatTypeEnums;
import cn.yitun.chat.yitunservercommonlib.util.NumUtil;
import cn.yitun.chat.yitunservercommonlib.util.R;
import cn.yitun.chat.yitunserverimapicore.business.chat.service.UserChatHistoryService;
import cn.yitun.chat.yitunserverimbase.dao.userchat.UserChatContentDao;
import cn.yitun.chat.yitunserverimcore.general.main.biz.chat.manager.UserChatHistoryManager;
import cn.yitun.chat.yitunserverimcore.general.main.biz.chat.manager.UserChatManager;
import cn.yitun.chat.yitunserverimcore.general.main.biz.userchat.manager.UserManager;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.transform.Result;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * Description <br>
 * Date 2016-08-23 11:20:14<br>
 *
 * @author yitun<br>
 * @version 1.1
 */
@Service
@Slf4j
public class UserChatHistoryServiceImpl
		extends CrudServiceImpl<UserChatContentDao, UserChatContentDto, UserChatContentInfo, UserChatContentVo>
		implements UserChatHistoryService {

	@Resource
	UserChatHistoryManager userChatHistoryManager;
	@Resource
	UserManager userManager;
	@Resource
	UserChatManager userChatManager;

	/**
	 * 根据记录表id查询用户聊天记录（上翻，下拉方式的）
	 * 
	 * @param query
	 * @return
	 */
	public ResultMessage getUserChatLogListByStartId(UserChatContentDto query) {
		String direction = query.getDirection();
		Long sendUserId = query.getSendUserId();
		Long receiveUserId = query.getReceiveUserId();
		Long startId = query.getStartId();

		boolean latest = !"before".equals(direction);


		List<UserChatHistory> contents = new ArrayList<>();

		if (NumUtil.isValid(sendUserId) && NumUtil.isValid(receiveUserId)) {

			UserChatContentVo ucc = null;
			if (NumUtil.isValid(startId)) {
				ucc = dao.getVO(startId);
			}

			List<UserChatContentVo> chatContentList = dao.getUserChatContentList(receiveUserId, sendUserId, startId, 0l, latest, ucc.getUpdateTime(), query.getSearchNum());
			contents = userChatHistoryManager.getUserChatHistoryList(chatContentList, false);
		}


		ResultMessage m = new ResultMessage();
		m.bodyPut("sendUserId", sendUserId);
		m.bodyPut("receiveUserId", receiveUserId);
		m.bodyPut("contents", contents);
		m.bodyPut("direction", latest ? "after" : "before");
		return m;
	}

	/**
	 * 根据消息id查询用户聊天记录（上翻，下拉方式的）
	 * 
	 * @param query
	 * @return
	 */
	public ResultMessage getUserChatLogListByStartMessageKey(UserChatContentDto query) {
		String direction = query.getDirection();
		int pageNo = query.getCurrentPageNo();
		int pageSize = query.getPageSize();
		Long sendUserId = query.getSendUserId();
		Long receiveUserId = query.getReceiveUserId();
		Long startMessageId = query.getMessageId();

		boolean latest = UserChatTypeEnums.CHAT_DIRECTION_BEFORE.getType().equals(direction);

		PageHelper.startPage(pageNo, pageSize);

		List<UserChatHistory> contents = new ArrayList<>();

		if (NumUtil.isValid(sendUserId) && NumUtil.isValid(receiveUserId)) {

			UserChatContentVo ucc = null;
			if (NumUtil.isValid(startMessageId)) {
				ucc = dao.getUserChatContentByMessageId(receiveUserId, sendUserId, startMessageId);
			}
			long times = System.currentTimeMillis();
			if (ucc != null)
				times = ucc.getUpdateTime();

			List<UserChatContentVo> chatContentList = dao.getUserChatContentList(receiveUserId, sendUserId, 0l, startMessageId, latest, times, query.getSearchNum());
			contents = userChatHistoryManager.getUserChatHistoryList(chatContentList, true);

		}

		return new ResultMessage(R.param("page", new PageInfo<>(contents)).put("direction", !latest ? UserChatTypeEnums.CHAT_DIRECTION_BEFORE.getType() : UserChatTypeEnums.CHAT_DIRECTION_AFTER.getType()));
	}

	/**
	 * 分页查询聊天记录
	 * 
	 * @param chatQuery
	 * @return
	 */
	public ResultMessage queryUserChatLogList(UserChatContentDto chatQuery) {
		Long sendUserId = chatQuery.getSendUserId();
		Long receiveUserId = chatQuery.getReceiveUserId();
		List<UserChatHistory> contents = new ArrayList<>();

		if (NumUtil.isValid(sendUserId) && NumUtil.isValid(receiveUserId)) {

			UserChatHistoryDto query = new UserChatHistoryDto();

			query.setChatReceiveUserId(receiveUserId);
			query.setChatSendUserId(sendUserId);

			contents = queryUserChatContentList(query);
		}

		ResultMessage m = new ResultMessage();
		m.bodyPut("sendUserId", sendUserId);
		m.bodyPut("receiveUserId", receiveUserId);
		m.bodyPut("contents", contents);
		return m;
	}

	/**
	 * 用户聊天记录
	 * @param query
	 * @return
	 */
	public List<UserChatHistory> queryUserChatContentList(UserChatHistoryDto query) {
		List<UserChatContentVo> chatContentList = dao.queryUserChatContentList(query);
		List<UserChatHistory> contents = userChatHistoryManager.getUserChatHistoryList(chatContentList, true);
		return contents;
	}

	/**
	 * 
	 * Date 2019-02-17 19:16:27<br>
	 * Description 获取离线消息信息
	 * 
	 * @param receiveUserId
	 * @return
	 * @author yitun<br>
	 * @version 1.1
	 */
	public List<Long> getOfflineUserIdList(Long receiveUserId) {
		List<Long> list = dao.getOfflineUserIdList(receiveUserId);
		return list;
	}

	/**
	 * 
	 * Date 2019-02-17 19:16:00<br>
	 * Description 更新消息为已读
	 * 
	 * @param receiveUserId
	 * @param sendUserId
	 * @author yitun<br>
	 * @version 1.1
	 */
	public void updateUserOfflineMessageToRead(Long receiveUserId, Long sendUserId, Long contentId, Long messageId) {
		dao.updateToRead(receiveUserId, sendUserId, contentId, messageId);
	}

	/**
	 * 
	 * Date 2019-02-17 19:15:40<br>
	 * Description 获取离线消息组合数量<br>
	 * 数据结构：[{"sendUserId":"110","count":100},{"sendUserId":"120","count":12},{
	 * "sendUserId":"119","count":19}]
	 * 
	 * @param query
	 * @return
	 * @author yitun<br>
	 * @version 1.1
	 */
	public List<UserOfflineCount> getOfflineCountList(UserChatContentDto query) {
		Long receiveUserId = query.getReceiveUserId();
		PageHelper.startPage(query.getCurrentPageNo(), query.getPageSize());
		List<UserOfflineCount> list = dao.getOfflineCountList(receiveUserId);
		return list;
	}

	/**
	 * 
	 * Date 2019-02-17 19:14:59<br>
	 * Description 获取指定相送离线消息的数量组合数量<br>
	 * 数据结构：[{"sendUserId":"110","count":100},{"sendUserId":"120","count":12},{
	 * "sendUserId":"119","count":19}]
	 * @param query
	 * @return
	 * @author yitun<br>
	 * @version 1.1
	 */
	public List<UserOfflineCount> getOfflineCountListBySendUserIds(UserChatContentDto query) {
		List<UserOfflineCount> list = dao.getOfflineCountListBySendUserIds(query.getReceiveUserId(), query.getSendUserIds());
		return list;
	}

	/**
	 * 添加用户聊天历史记录
	 * @param isSend
	 * @param sendUserId
	 * @param receiveUserId
	 * @param messageId
	 * @param chatItemList
	 */
	public void addUserChatHistory(
			boolean isSend,
			Long sendUserId,
			Long receiveUserId,
			Long messageId,
			List<ChatItem> chatItemList) {
		UserVo sendUserData = userManager.getUserDataById(sendUserId);
		UserVo receiveUserData = userManager.getUserDataById(receiveUserId);
		if (null != sendUserData && null != receiveUserData) {
			userChatManager.addUserChatHistory(isSend, sendUserData, receiveUserData, messageId, chatItemList);
		}
	}

	/**
	 * 获取未读 计数
	 * @param query
	 * @return
	 */
	@Override
	public ResultMessage queryUserChatUnreadCount(UserChatContentDto query) {
		ResultMessage rm = new ResultMessage();
		rm.bodyPut("count", userChatManager.queryUserChatUnreadCount(query));
		return rm;
	}


	/**
	 * 获取未读 列表
	 * @param query
	 * @return
	 */
	@Override
	public ResultMessage queryUserChatUnreadList(UserChatContentDto query) {
		ResultMessage rm = new ResultMessage();
		PageHelper.startPage(query.getCurrentPageNo(), query.getPageSize());
		rm.bodyPut("page", userChatManager.queryUserChatUnreadList(query));
		return rm;
	}
}
